package search

import (
	"github.com/astaxie/beego/httplib"
	"fmt"
	"strings"
)

type TtSearch struct {
	Data []struct{
		Title string `json:"title"`
	}
}

func ToutiaoSearch(word string) int{
	api := fmt.Sprintf(`https://www.toutiao.com/search_content/?offset=0&format=json&keyword=%s&autoload=true&count=20&cur_tab=1&from=search_tab`,word)
	results := TtSearch{}
	err :=  httplib.Get(api).ToJSON(&results)
	if err != nil{
		return 100
	}

	max := 0
	for i,result := range results.Data{
		if i > 3{
			break
		}
		if score := repeat(word,result.Title);score > max{
			max = score
		}
	}

	return max
}

func repeat(result ,title string) int{
	allLenght := len([]rune(result))
	if allLenght == 0 {
		return 0
	}
	runeTitles := []rune(title)
	//runeW2 := []rune(w2)

	for _,runeTitle := range runeTitles{
		result = strings.Replace(result,string(runeTitle),"",1)
	}
	lessLenght := len([]rune(result))
	return (allLenght-lessLenght)*100/allLenght
}

func main() {
	word := `想生二胎的父母，你们这些账算过？过来人告诉你：花费像个无底洞`
	result := ToutiaoSearch(word)
	fmt.Println(result)
}




